package com.hzc.springchan.service.impl.verifycode;

import com.hzc.springchan.constant.Business;
import com.hzc.springchan.constant.System;
import com.hzc.springchan.enums.impl.EmsBusiness;
import com.hzc.springchan.service.IVerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @Description: 邮箱验证码服务
 * @Author: chen990627
 * @Date: 2022/11/01
 **/
@Service(System.VerifyCodeBean.EMS)
public class EmsVerifyCodeServiceImpl implements IVerifyCodeService {

    private final static String REDIS_KEY_PREFIX = "ems:";

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromUser;

    @Override
    public VerifyResponse doSendCode(VerifyRequest request) {

        EmsBusiness emsBusiness = (EmsBusiness) request.getBusiness();

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(emsBusiness.getSubject());
        mailMessage.setText(emsBusiness.getText(request.getVerifyCode()));
        mailMessage.setFrom(fromUser);
        mailMessage.setTo(request.getReceiver());
        mailSender.send(mailMessage);
        return VerifyResponse.success();
    }

    @Override
    public String redisKey(VerifyRequest request) {
        return new StringBuilder(REDIS_KEY_PREFIX)
                .append(request.getBusiness().businessName())
                .append(Business.SymbolStr.UNDERLINE)
                .append(request.getReceiver())
                .toString();
    }
}
